package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/*
线程任务
负责与特定的客服进行HTTP交互
 */
public class ClientHandler implements Runnable {
    private Socket socket;//提升作用域

    public ClientHandler(Socket socket) {//重写构造方法
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //1解析请求（请求头，消息头，消息正文）
            String line = readLine();//封装了一个读取的方法
            System.out.println("请求行：" + line);

            //请求行获取相关信息
            String method;//请求方式
            String uri;//抽象路径
            String protocol;//协议版本

            String[] data = line.split("\\s");//正则表达式，
            method = data[0];
            uri = data[1];
            protocol = data[2];
            System.out.println("method-请求方式:" + method);
            System.out.println("uri-抽象路径:" + uri);
            System.out.println("protocol-协议版本:" + protocol);
            Map<String, String> headers = new HashMap<>();
            while (true){
                //读消息头
                line = readLine();
                if (line.isEmpty()){//如果读取的是空字符串说明单独读取了CRLF
                    break;
                }
//                String[] data1 = line.split(":\\s");
//                headers.put(data1[0],data1[1]);
                //Connection:keep-alive
                System.out.println("消息头："+line);
                data = line.split(":\\s");
                headers.put(data[0],data[1]);

            }
            System.out.println("headers:"+headers);
//            line = readLine();
//            System.out.println("消息头："+line);
//            System.out.println("heeaders:"+);

            //2处理请求
            //3发送响应
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();//响应后断开连接
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String readLine() throws IOException {//解决代码复用
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char cur = 'a';//保存本次读取到的字符
        char pre = 'a';//保存上次读取到的字符串
        int d;
        while ((d = in.read()) != -1) {
            cur = (char) d;
            if (pre == 13 && cur == 10) {//判断是否连续读取到了回车+换行
                break;
            }
            builder.append(cur);
            pre = cur;//下次循环前将本次读取到的字符串记为
        }
        return builder.toString().trim();
    }
}
